#include "imageeditor.h"

#include <qevent.h>

ImageEditor::ImageEditor(QString imagePath,QWidget *parent)
    : QGraphicsView(parent)
    , mImagePath(imagePath)
    , mImage{QPixmap(imagePath)}
{
    setAttribute(Qt::WA_DeleteOnClose);
    Init();
}

void ImageEditor::Init()
{
    QGraphicsView::setScene(new QGraphicsScene(this));
    QGraphicsView::scene()->addPixmap(mImage);
}

QPixmap ImageEditor::Pixmap() const
{
    return mImage;
}

QString ImageEditor::ImagePath() const
{
    return mImagePath;
}

void ImageEditor::setZoomFactor(double zoomFactor)
{
    mZoomFactor = zoomFactor;
}

void ImageEditor::fitInView(const QRectF &rect, Qt::AspectRatioMode aspectRatioMode)
{
    // 1、首先需要还原成 1 : 1
    QRectF unity = transform().mapRect(QRectF(0, 0, 1, 1));
    scale(1 / unity.width(), 1 / unity.height());

    int margin = 2;
    QRectF viewRect = viewport()->rect().adjusted(margin, margin, -margin, -margin);
    QRectF sceneRect = transform().mapRect(rect);

    // 自适应窗口的scale * mZoomFactor
    qreal xratio = viewRect.width() / sceneRect.width() * mZoomFactor;
    qreal yratio = viewRect.height() / sceneRect.height() * mZoomFactor;

    xratio = yratio = qMin(xratio, yratio);
    scale(xratio, yratio);
    centerOn(sceneRect.center());
}

void ImageEditor::resizeEvent(QResizeEvent *event)
{
    // qDebug("ImageEditor::resizeEvent, width=%d, height=%d", event->size().width(), event->size().height());
    if (!scene()) {
        return;
    }

    fitInView(scene()->sceneRect(), Qt::KeepAspectRatio);
    QGraphicsView::resizeEvent(event);
}
